# Copyright (c) 2024, json_wang and contributors
# For license information, please see license.txt

from frappe.utils import cint, cstr, flt, getdate, datetime, get_first_day, get_last_day, formatdate
from frappe.model.document import Document
import frappe
from frappe import _
from erpnext.accounts.utils import get_balance_on
import datetime
from frappe.utils import getdate
import pandas as pd


class AC_BalanceSheet(Document):
    @frappe.whitelist()
    def build_report(self):
        doc = frappe.get_doc("AC_BalanceSheet_Config", self.config_version)
        if not doc:
            frappe.throw("没有找到当前公司的报表配置!")
        end_date = get_last_day(getdate(self.report_date))
        start_date = end_date.replace(year=end_date.year, month=1, day=1)
        # print(start_date)
        acct_list = []
        for item in doc.items:
            # print(item.acct)
            opening_balance = get_balance_on(item.acct, start_date)
            closing_balance = get_balance_on(item.acct, end_date)
            acct_list.append(
                {
                    "报表项目": item.rpt_item,
                    "科目": item.acct,
                    "期初": opening_balance * item.rate,
                    "期末": closing_balance * item.rate,
                    "序号": item.sort_id,
                }
            )
        # 从字典创建DataFrame
        df = pd.DataFrame.from_dict(acct_list)
        print(df)
        summary = (
            df.groupby("报表项目")
            .agg({"期初": "sum", "期末": "sum", "序号": "max"})
            .reset_index()
            .sort_values(by="序号")
        )
        print(summary)
        # temp = df[["科目","期初","期末"]].rename(columns={'科目': '报表项目'})
        # summary1 = pd.concat([summary,temp]).reset_index(drop=True)
        # print(summary1)
        self.childs = []
        for index, row in summary.iterrows():
            self.append(
                "childs",
                {
                    "rpt_item": row["报表项目"],
                    "opening_balance": row["期初"],
                    "closing_balance": row["期末"],
                    "sort_id": row["序号"],
                },
            )
        self.refresh_time = datetime.datetime.now()
        self.save(ignore_permissions=True)
